package com.smile.service.job;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.smile.mapper.AirportInfoMapper;
import com.smile.mapper.DroneMapper;
import com.smile.mapper.FlightStatisticsMapper;
import com.smile.mapper.FlightTaskMapper;
import com.smile.model.domain.*;

import com.smile.service.entity.drc.HeartBeatData;
//import com.xxl.job.core.context.XxlJobHelper;
//import com.xxl.job.core.handler.annotation.XxlJob;
import com.smile.service.service.MqttMessageSender;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Component
public class DeviceJob {

    @Autowired
    private MqttMessageSender mqttMessageSender;

    @Autowired
    private AirportInfoMapper airportInfoMapper;

    @Autowired
    private FlightStatisticsMapper flightStatisticsMapper;

    @Autowired
    private FlightTaskMapper flightTaskMapper;

    @Autowired
    private DroneMapper droneMapper;

    /**
     * 40秒定时统计
     */
    @Scheduled(fixedRate = 40000)
    public void statistics() {
        System.out.println("执行统计");
        QueryWrapper<FeisuanFlightTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", "4");
        queryWrapper.isNotNull("airport_id");
        queryWrapper.isNotNull("end_time");
        queryWrapper.eq("is_statistics",0);
        List<FeisuanFlightTask> feisuanFlightTasks = flightTaskMapper.selectList(queryWrapper);

        if (feisuanFlightTasks != null && feisuanFlightTasks.size() > 0) {
            for (FeisuanFlightTask flightTask : feisuanFlightTasks) {
                QueryWrapper<FeisuanFlightStatistics> queryWrapper1 = new QueryWrapper<>();
                queryWrapper1.eq("statistics_date", flightTask.getCreateTime().toLocalDate());
                queryWrapper1.eq("airport_id",flightTask.getAirportId());
                queryWrapper1.eq("drone_id",flightTask.getDroneId());
                queryWrapper1.eq("organization_id",flightTask.getOrganizationId());
                queryWrapper1.last("limit 1");
                FeisuanFlightStatistics statistics = flightStatisticsMapper.selectOne(queryWrapper1);
                if (statistics != null) {
                    statistics.setTaskCount(statistics.getTaskCount() + 1);
                    statistics.setTotalTaskTime(statistics.getTotalTaskTime() + flightTask.getFlightTime());
                    statistics.setTotalTaskDistance(statistics.getTotalTaskDistance() + flightTask.getFlightDistance());
                    flightStatisticsMapper.updateById(statistics);
                }else{
                    FeisuanFlightStatistics  statistics1 = new FeisuanFlightStatistics();
                    statistics1.setTaskCount(1);
                    statistics1.setTotalTaskTime(flightTask.getFlightTime());
                    statistics1.setTotalTaskDistance(flightTask.getFlightDistance());
                    statistics1.setDroneId(flightTask.getDroneId());
                    statistics1.setOrganizationId(flightTask.getOrganizationId());
                    statistics1.setAirportId(flightTask.getAirportId());
                    statistics1.setStatisticsDate(flightTask.getCreateTime().toLocalDate());
                    flightStatisticsMapper.insert(statistics1);
                }
                flightTask.setIsStatistics(1);
                flightTaskMapper.updateById(flightTask);
            }
        }
    }

    @Scheduled(fixedRate = 2000)
    public void heartbeat() {
        JSONObject jsonObject = new JSONObject();
        HeartBeatData heartBeatData = new HeartBeatData();
        heartBeatData.setTimestamp(System.currentTimeMillis());
        jsonObject.put("method", "heart_beat");
        System.out.println(jsonObject.toJSONString());

        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formattedDate = sdf.format(date);
        System.out.println(formattedDate);
        jsonObject.put("data", heartBeatData);
        try {
            this.process(jsonObject.toJSONString());
        } catch (MqttException e) {
            System.out.println(e.getMessage());
            throw new RuntimeException(e);
        }
    }

    public Boolean process(String data) throws MqttException {
//        MqttMessage message = new MqttMessage();
//        message.setQos(0);
//        message.setRetained(true);
//        message.setPayload(data.getBytes());
        //获取所有在线的机场
        QueryWrapper<FeisuanAirportInfo> queryWrapper = new QueryWrapper<>();
        long timestamp = System.currentTimeMillis()-5000;
        Date date = new Date(timestamp);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String formattedDate = sdf.format(date);
        queryWrapper.gt("modify_time", formattedDate);
        //维护在线的心跳
        List<FeisuanAirportInfo> list = airportInfoMapper.selectList(queryWrapper);
        for (FeisuanAirportInfo feisuanAirportInfo : list) {
            mqttMessageSender.sendMsg("thing/product/" + feisuanAirportInfo.getGatewaySn() + "/services", data);
            mqttMessageSender.sendMsg("thing/product/" + feisuanAirportInfo.getGatewaySn() + "/drc/down", data);
        }
        return Boolean.TRUE;
    }


    /**
     * 定时统计设备的飞行数据
     */
    @Scheduled(fixedRate = 40000)
    public void statisticsDrone() {
        System.out.println("更新无人机统计数据");
        QueryWrapper<FeisuanDrone> queryWrapper = new  QueryWrapper<>();
        List<FeisuanDrone> feisuanDrones = droneMapper.selectList(queryWrapper);
        for (FeisuanDrone feisuanDrone : feisuanDrones) {
            CountFlight  countFlight = flightStatisticsMapper.countFlight(feisuanDrone.getId());
            if (countFlight != null) {
                UpdateWrapper<FeisuanDrone> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("id", feisuanDrone.getId());
                updateWrapper.set("total_task_distance", countFlight.getDistance());
                updateWrapper.set("total_task_time", countFlight.getTime());
                updateWrapper.set("task_count", countFlight.getNum());
                droneMapper.update(new FeisuanDrone(), updateWrapper);
            }
        }
    }
}
